//
//  HMStatusDALViewModel.swift
//  WeiBo
//
//  Created by Feng on 2017/6/18.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit

//删除本地存储微博的最大时间限制
let MaxTimeInteveral: Double = -(7 * 24 * 3600)

class HMStatusDALViewModel: NSObject {

    //  微博数据访问层，用于封装微博数据缓存等操作

    /*
     微博缓存数据的逻辑
     1. 判断本地是否有微博缓存数据
     2. 如果本地有微博缓存是直接使用本地缓存数据
     3. 如果本地没有微博缓存数据直接从网络请求微博数据
     4. 微博数据请求成功后要缓存到本地
     5. 微博数据缓存到本地以后返回从网络请求微博数据
     */

    //1. 判断本地是否有微博缓存数据
    class func checkCacheData(maxid: Int64, sinceid: Int64) -> [[String: Any]]
    {
        let userid = HMUserAccountViewModel.sharedUserAccount.userAccount?.uid
        
        var sql = "select * from t_statuses where userid = \(userid!)\n"
        
        //判断是下拉刷新还是上拉加载
        if maxid > 0
        {
            //上拉加载
            sql += "and id < \(maxid)\n"
        }
        else
        {
            //下拉刷新
            sql += "and id > \(sinceid)\n"
        }
        
        sql += "order by id desc limit 20\n"
        
        //执行sql
        let localDictArray = HMSqliteManager.sharedManager.selectDictArray(sql: sql)
        
        var statusDictArray = [[String: Any]]()
        for localDict in localDictArray
        {
            let statusData = localDict["status"] as! Data
            
            let statusDic = try! JSONSerialization.jsonObject(with: statusData, options: []) as! [String: Any]
            
            statusDictArray.append(statusDic)
        }
        
        return statusDictArray
    }
    
    //缓存微博数据
    class func cacheData(statusDicArray: [[String: Any]])
    {
        let userid = HMUserAccountViewModel.sharedUserAccount.userAccount?.uid
        
        let sql = "insert into t_statuses(id, status, userid) values (?,?,?)"
        
        HMSqliteManager.sharedManager.inTransaction { (db, rollBack) in
            for statusDic in statusDicArray
            {
                let id = statusDic["id"] as! Int64
                
                //  微博字典对应的二进制
                let statusData = try! JSONSerialization.data(withJSONObject: statusDic, options: [])
                let result = db?.executeUpdate(sql, withArgumentsIn: [id, statusData, userid!])
                
                if result == false
                {
                    rollBack?.pointee = true
                    break
                }
            }
        }
    }
    
    //删除缓存数据
    class func clearCacheData()
    {
        //获取7天前时间
        let maxDateTime = Date().addingTimeInterval(MaxTimeInteveral)
        let dt = DateFormatter()
        dt.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let maxDateStr = dt.string(from: maxDateTime)
        
        let sql = "delete from t_statuses where time < ?"
        
        HMSqliteManager.sharedManager.inDatabase { (db) in
            let result = db?.executeUpdate(sql, withArgumentsIn: [maxDateStr])
            
            if result == true
            {
                print("删除缓存数据成功, 影响了\(db?.changes())")
            }
            else
            {
                print("删除数据失败")
            }
        }
    }
}
